package com.java.escape.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName Main
 * @Description TODO
 * @Author wyp
 * @Date 2023/9/15 11:23
 * @Version 1.0
 */
public class Main {
    //1.反射不能调用父类的方法
    public static void require() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<Boss> aClass = Boss.class;
//        Method boss = aClass.getDeclaredMethod("worker", String.class);
        Method method = returnSuperMethod(aClass, "worker", new Class[]{String.class});
        if (method != null) {
            System.out.println(method.invoke(aClass.getConstructor().newInstance(), "hello"));
        }
    }

    //2.解决办法
    public static Method returnSuperMethod(Class<?> target, String methodName,
                                           Class<?>[] argTypes) {
        Method method = null;
        try {
            method = target.getDeclaredMethod(methodName, argTypes);
            method.setAccessible(true);
        } catch (NoSuchMethodException e) {
            System.out.println("Can not get method!" + methodName + "from" + target.getName());
        }
        if (method == null && target != Object.class) {
            return returnSuperMethod(target.getSuperclass(), methodName, argTypes);
        }
        return method;


    }

    public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
//        Class<Boss> aClass = Boss.class;
//        Method[] methods = aClass.getMethods();
//        //1.反射获取的方法参数类型要保持一致
//        Method numeric = aClass.getMethod("numeric", Integer.class);
//        System.out.println(numeric.invoke(aClass.getConstructor().newInstance(), 19));
//        require();
        String str1 = "123";
        System.out.println(str1.getClass());
        str1 = "sda";
        System.out.println(str1.getClass());
        System.out.println(str1);
    }
}
